/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JFreeChartExtensions.Fitters;

import JFreeChartExtensions.Series.XYExtendedIntervalSeries;
import JFreeChartExtensions.Series.XYRegressionSeries;
import org.apache.commons.math.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.fitting.PolynomialFitter;
import org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;

/**
 *
 * @author Nobody
 */
public class PolynomialReggresion implements IReggression {

    private int degree = 2;
    public int PRECISE = 100;
    private String lastFunctionFormula;

    public PolynomialReggresion(int degree) {
        this.degree = degree;
    }

    @Override
    public XYRegressionSeries regress(XYExtendedIntervalSeries series) throws OptimizationException {

        XYRegressionSeries regr = null;

        LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
        PolynomialFitter fitter = new PolynomialFitter(degree, optimizer);
        for (int i = 0; i < series.getItemCount(); ++i) {
            fitter.addObservedPoint(1, (Double) series.getX(i), series.getYValue(i));
        }
        PolynomialFunction polynomialFunction = fitter.fit();
        lastFunctionFormula = polynomialFunction.toString();
        regr = new XYRegressionSeries(lastFunctionFormula);
        for (double x = series.getMinX(); x < series.getMaxX(); x += (series.getMaxX() - series.getMinX()) / PRECISE) {
            regr.add(x, polynomialFunction.value(x));
        }
        return regr;
    }

    @Override
    public String toString() {
        return "PolynomialReggresion(" + degree + " degree)";
    }

  
}
